package com.eobard.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.eobard.entity.User;
import com.eobard.utils.*;
import com.eobard.vo.TokenVo;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Eobard_Thawne
 * @version 1.0
 * @date 2022/8/6 -17:21
 */

/**
 * 登录成功处理器类
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 当登录成功时,将登录成功的对象通过JSON返回给前端
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取当前登录对象
        User user= (User) authentication.getPrincipal();
        //生成token
        String token = jwtUtils.generateToken(user);
        //设置token签名密钥及过期时间
        long expireTime = Jwts.parser()                                     //获取DefaultJwtParser对象
                .setSigningKey(jwtUtils.getSecret())                        //设置签名的密钥
                .parseClaimsJws(token.replace("jwt_", "")) //生成的token默认有jwt_下标,将其替换
                .getBody().getExpiration().getTime();                       //获取token过期时间
        //创建登录结果对象
        LoginResult loginResult = new LoginResult(user.getId(),ResultCode.SUCCESS,token,expireTime);
        //将对象转为JSON,消除循环依赖
        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);

        //通过流对象输出JSON到前端
        ResponseUtils.writeJSON(result,response);

        //将token信息保存到redis中
        redisUtils.set(TokenVo.USER_TOKEN_PREFIX +token,token,jwtUtils.getExpiration()/1000);
    }
}
